import Tips from "./h5plus/Tips";
import {
    request
} from "./Request";

/**
 * HTTP工具类
 * 
 * @export
 * @class Http
 */
export default class Http {
    static async request(method, url, data, loading) {
        const param = {
            url: url,
            method: method,
            data: data
        };
        if (loading) {
            Tips.loading();
        }
        const res = await request(param);
        if (loading) {
            Tips.loaded();
        }
        if (this.isSuccess(res)) {
            return res.data;
        } else {
            throw this.requestException(res);
        }
        
    }

    /**
     * 判断请求是否成功
     */
    static isSuccess(res) {
        const status = res.status;
        // 请求错误
        if (status !== 200) {
            return false;
        }
        const data = res.data;
        return !(data && res.statusText !== 'OK');
    }

    /**
     * 异常
     */
    static requestException(res) {
        const error = {};
        error.status = res.status;
        const serverData = res.data;
        const message = res.statusText;
        if (serverData) {
            error.message = message;
            error.serverData = serverData;
        }
        return error;
    }

    static get(url, data, loading = true) {
        return this.request('GET', url, data, loading);
    }

    static put(url, data, loading = true) {
        return this.request('PUT', url, data, loading);
    }

    static post(url, data, loading = true) {
        return this.request('POST', url, data, loading);
    }

    static patch(url, data, loading = true) {
        return this.request('PATCH', url, data, loading);
    }

    static delete(url, data, loading = true) {
        return this.request('DELETE', url, data, loading);
    }
}